package com.ruoyi.employee.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class OSSUtil {
    // yourEndpoint,填写Bucket所在地域对应的Endpoint。
    private static String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    // 填写Bucket名称。
    private static String bucketName = "wsy05";
    // 填写Object的完整路径。Object完整路径中不能包含Bucket名称。
    private static String objectName = "tx/";
    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。
    private static String accessKeyId = "LTAI5tQesYiaRV3oL7jJ9j93";
    private static String accessKeySecret = "4QMdm0Xbu9INORjhVfPZ7wdjMr0AEv";
    // 文件url前缀
    private static String furl = "https://wsy05.oss-cn-beijing.aliyuncs.com/";

    // 文件上传方法
    public static String upload(String fileName, InputStream in) {
        // 组合objectName
        String objectNameUrl = objectName + fileName;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,
                accessKeySecret);
        // 上传
        PutObjectResult re = ossClient.putObject(bucketName, objectNameUrl, in);
        //关闭连接
        ossClient.shutdown();
        // 返回文件的url
        // https://xiao0214.oss-cn-hangzhou.aliyuncs.com/tx/....
        return furl + objectName + fileName;
    }

    //文件下载方法
    public static void download(String fileName, OutputStream out) throws
            IOException {
        // 组合objectName
        String objectNameUrl = objectName + fileName;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,
                accessKeySecret);
        // 下载
        OSSObject object = ossClient.getObject(bucketName, objectNameUrl);
        InputStream in = object.getObjectContent();
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = in.read(bytes)) != -1) {
            out.write(bytes, 0, len);
        }
        out.close();
        in.close();
        //关闭连接
        ossClient.shutdown();
    }
}